﻿<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="PageTitle" runat="server">
    <title>易得桌面</title>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="PageStyles" runat="server">
    <link href="../../Content/fullcalendar.css" rel="stylesheet" type="text/css" />
    <link href="../../Content/table_jui.css" rel="stylesheet" type="text/css" />
    <style type="text/css">
        #attendanceChange
        {
            width: 60px;
            height: 30px;
            font-size: 14px;
        }
        #menu_changeAttendanceType
        {
            width: 80px;
            height: 60px;
        }
        #dialog_confirmCheckAttendance .p_title
        {
            font-size: 18px;
        }
        #dialog_confirmCheckAttendance .p_body
        {
            font-size: 14px;
        }
    </style>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="PageScripts" runat="server">
    <script src="../../Scripts/jquery.dataTables.js" type="text/javascript"></script>
    <script src="../../Scripts/fullcalendar.js" type="text/javascript"></script>
    <script src="../../Scripts/json.js" type="text/javascript"></script>
    <script src="../../Scripts/pinyin.js" type="text/javascript"></script>
    <script language="JavaScript" type="text/javascript">
    //************* URL常量

    var URL_ATTENDANCE_TYPE_STATUS = '/attendance/AttendanceTypeStatus';
    var URL_ATTENDANCE_LIST_PERDAY = '/attendance/AttendanceListPerDay';
    var URL_ATTENDANCE_DOCHECKATTENDANCE = '/attendance/DoCheckAttendance';


    //************* 全局变量

    var g_Var = {
        'currentTime': null,
        'attendanceType': null,
        'isAbnormal': null,
        'isDuplicated': null,
        'currentUser': null,
        'hasCheckedAttendance': false,
    };

    //************* 常量定义

    var StaticResource = {
        'AttdendacneTypeResource': {
            'onDuty': '上班',
            'offDuty': '下班'
        }
    };


    var convertor = {
        "姓名": function (item) {
            return item.User.Name;
        },
        "部门": function (item) {
            return item.User.Dept.DeptName;
        },
        "时间": function (item) {
            var sign = "<span class='important'>*</span>";
            var nbsp = "<span class='important'>&nbsp</span>";
            var attendanceTime = Date.fromEpoch(item.ActionTime);
            var attendanceTimeFormat = attendanceTime.toFullTimeFormat();

            if (item.IsAbnormalAttendance) {
                return sign + attendanceTimeFormat;
            }
            else {
                return nbsp + attendanceTimeFormat;
            }

        },
        "类型": function (item) {
            return StaticResource.AttdendacneTypeResource[item.AttendanceType];
        },
        "备注": function (item) {
            return item.Explanation;
        }
    };
    //************* Accessor访问器

    var EzAccessor = {};
    if (ezmock.IS_MOCKED) {

        var mock_currentTime = { "CurrentTime": 1348449559 };

        var mock_currentDefaultAttendance = {
            "AttendanceType": 'offDuty',
            "IsAbnormal": false,
            "IsDuplicated": true
        };
        var mock_attendanceTypeStatus = {
            "AttendanceType": 'offDuty',
            "IsAbnormal": false,
            "IsDuplicated": true
        };

        var mock_currentUser = {
            "Id": "0c9d7c0c-04a5-4ae2-97a1-d7bbc38f5c66",
            "Name": "杨裕欣", "UserName": "yuxin",
            "Dept": {
                "Id": "bd3474a8-6c2d-43ef-bf42-b06827a216f6",
                "DeptName": "软件工程部",
                "GroupId": "9ad96dac-88d8-4315-bfdb-9931c8f3cb7c"
            }
        };
        var mock_json = { "AttendanceInfoList":
	        [
	         { "Id": "960657b5-64db-4044-9948-7f8362601ee5",
	             "User": {
	                 "Id": "ce36c495-38cc-4b7e-875e-364ff8e087b5",
	                 "Name": "卢春叶",
	                 "UserName": "lcy",
	                 "Dept": {
	                     "Id": "e8731583-3397-4f28-aa43-c006dbe750a2",
	                     "DeptName": "行政部",
	                     "GroupId": "c875149c-ee0c-48e2-bd2d-39d870f49b67"
	                 }
	             },
	             "Date": 1280419200,
	             "AttendanceType": "offDuty",
	             "ActionTime": 1380459734,
	             "Explanation": "Hello",
	             "IsAbnormalAttendance": false
	         }
            ]
        };

        var mock_dayInfo = {
            "Date": "1243180800",
            "IsNeedToWork": false,
            "HolidayInfo": {
                "Name": "国庆节"
            },
            "ExtraShiftInfo": {
                "Name": "年假"
            },
            "IsWeekEnd": false
        };

        var mockEzAccessor = {
            'getBasicInfo': function () {
                g_Var['currentTime'] = Date.fromEpoch(mock_currentTime["CurrentTime"]);
                g_Var['attendanceType'] = mock_currentDefaultAttendance.AttendanceType;
                g_Var['isAbnormal'] = mock_currentDefaultAttendance.IsAbnormal;
                g_Var['isDuplicated'] = mock_currentDefaultAttendance.IsDuplicated;
                g_Var['currentUser'] = mock_currentUser;
            },
            'getDayInfo': function () {
                return mock_dayInfo;

            },
            
            'doChangeAttendanceType': function () {
                menu_changeAttendanceTypeCallback(mock_json);
            },

            'doCheckAttendance': function () {
                var statusInfo = { "Status": "Success", "Info": "考勤成功！", "Data": null };
                $.displayStatusInfo(statusInfo);
                initiExplainText();

                g_Var.hasCheckedAttendance = true;

                // 隐藏考勤按钮跟备注信息
                $("#btnCheck").hide();
                $("#listRemark").hide();
            },
            'doUpdateAttendanceList': function () {
                bindAttendanceList(mock_json.AttendanceInfoList);
            }

        };

        EzAccessor = mockEzAccessor;
    } else {
        var realEzAccessor = {
            'getBasicInfo': function () {
                                                g_Var['currentTime'] = Date.fromEpoch(<%= ViewData["CurrentTime"] %>);
                                                g_Var['isAbnormal'] = <%= ViewData["IsAbnormal"] %>;
                                                g_Var['isDuplicated'] = <%= ViewData["IsDuplicated"] %>;
                                                g_Var['attendanceType'] = '<%= ViewData["CurrentDefaultAttendance"] %>';
                                                g_Var['currentUser'] = <%= ViewData["CurrentUser"] %>;
            },
            'getDayInfo': function () {
                                                return <%= ViewData["DayInfo"] %>;
            },
            'getAttendanceConfig': function(){
                 return <%= ViewData["AttendanceConfig"] %>;
            },
            'doChangeAttendanceType': function () {
                $(document).ajaxBusy('begin');
                $.getJSON(
                  URL_ATTENDANCE_TYPE_STATUS,
                  { 'attendanceTypeStr': g_Var['attendanceType'] },
                  menu_changeAttendanceTypeCallback
                  );
            },

            'doCheckAttendance': function () {
                var explainText = $('#explainText').val().htmlEncode();
                if ($('#explainText').defaultText()) {
                    explainText = "";
                }
                if (explainText.length > 80){
                    var statusInfo = { 'Status': 'Error', 'Info': '考勤备注不能超过80个字符！' };
                    $.displayStatusInfo(statusInfo);
                    return false;
                }

                $(document).ajaxBusy('begin');
                $.post(URL_ATTENDANCE_DOCHECKATTENDANCE, {
                    'attendanceTypeStr': g_Var['attendanceType'],
                    'explainText': explainText,
                    'isAbnormalAttendance': g_Var['isAbnormal']
                }, function (e) {
                    initiExplainText();
                    $.displayStatusInfo(e);

                    g_Var.hasCheckedAttendance = true;

                    $.getJSON(
                      URL_ATTENDANCE_TYPE_STATUS,
                      { 'attendanceTypeStr': g_Var['attendanceType'] },
                      menu_changeAttendanceTypeCallback
                    );

                });

            },

            'doUpdateAttendanceList': function () {
                $(document).ajaxBusy('begin');
                //缓冲数据加载
                bindAttendanceList();
                $.getJSON(
                      URL_ATTENDANCE_LIST_PERDAY,
                      { 'attendanceTypeStr': g_Var['attendanceType'], 'dateEpoch': g_Var['currentTime'].toEpoch() },
                      function (e) {
                          bindAttendanceList(e.AttendanceInfoList);
                          $(document).ajaxBusy('end');
                      });
            }
        };
        EzAccessor = realEzAccessor;
    }


    function signedCurrentTime(currentTime) {

        var sign = "<span class='important'>*</span>";
        var nbsp = "<span class='important'>&nbsp</span>";

        if (!g_Var['isAbnormal']) {
            currentTime = sign + currentTime;
        } else {
            currentTime = nbsp + currentTime;
        }
        return currentTime;
    }


    function menu_changeAttendanceTypeCallback(e) {
        g_Var['isAbnormal'] = e.IsAbnormal;
        g_Var['isDuplicated'] = e.IsDuplicated;
        $(document).ajaxBusy('end');

        updateAttendanceList();
        updateCurrentStatus();
    }

    function changeAttendanceTypeCallback(targetAttendanceType) {
        if (g_Var['attendanceType'] != targetAttendanceType) {
            $(document).ajaxBusy('begin');
            g_Var['attendanceType'] = targetAttendanceType;

            $('#attendanceChange')
              .text(StaticResource.AttdendacneTypeResource[g_Var.attendanceType])
              .css({ 'font-weight': 'bold' });

            $('#attendanceChange').freeContent('close');

            EzAccessor.doChangeAttendanceType();

        } else {
            $('#attendanceChange').freeContent('close');
        }
    }

    function updateCurrentStatus() {
        // 显示考勤按钮跟备注信息
        $("#btnCheck").show();
        $("#listRemark").show();
        EzTipsManager.hideTipBox('tipDuplicated');
        if (!g_Var['isAbnormal']) {
            // 正常考勤
            $('#lblAbnormal').hide();
            EzTipsManager.hideTipBox('tipAbnormal');

            // 考勤重复
            if (g_Var.isDuplicated) {
                // 隐藏考勤按钮跟备注信息
                $("#btnCheck").hide();
                $("#listRemark").hide();
                EzTipsManager.showTipBox('tipDuplicated');
            }
        }
        else {
            // 非正常考勤
            $('#lblAbnormal').show();
            EzTipsManager.showTipBox('tipAbnormal');
        }

        if (g_Var.hasCheckedAttendance) {
            // 隐藏考勤按钮跟备注信息
            $("#btnCheck").hide();
            $("#listRemark").hide();
        }

        $('#attendanceChange')
          .text(StaticResource.AttdendacneTypeResource[g_Var['attendanceType']])
          .css({ 'font-weight': 'bold' });

    }

    function updateAttendanceList() {
        //更新考勤记录
        EzAccessor.doUpdateAttendanceList();
    }

    function bindAttendanceList(originalJson) {

        var attendanceData = g_Var['currentTime'].toFullChineseDateFormat();
        var data = DataConverterForDataTable.convertData(originalJson, convertor);
        var tblTitle = attendanceData
                        + "&nbsp"
                        + StaticResource.AttdendacneTypeResource[g_Var['attendanceType']]
                        + "考勤记录";

        data.bPaginate = false;
        data.bRetrieve = true;
        data.bFilter = false;
        data.bSort = false;
        data.bInfo = false;
        data.fnRowCallback = function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
            if (g_Var['currentUser'].Name == aData[0]) {
                // 当前用户自己的考勤记录，把背景换个颜色~
                $(nRow).css({
                    'background': '#62ad25',
                    'color': '#fff'
                });
            }
            return nRow;

        };


        $('#divAttendanceList')
          .empty();

        var tblAttendanceList = $('<table id="tblAttendanceList" class="tbl"/>')
          .appendTo('#divAttendanceList');

        $('#tblAttendanceList')
          .dataTable(data)
          .dataTableTitle(tblTitle);


        // 设置表格宽度
        var nameColumnHead = $('#tblAttendanceList thead tr th')[0];
        var deptColumnHead = $('#tblAttendanceList thead tr th')[1];
        var actionTimeColumnHead = $('#tblAttendanceList thead tr th')[2];
        var typeColumnHead = $('#tblAttendanceList thead tr th')[3];

        $(nameColumnHead).css({
            'width': '60px'
        });
        $(deptColumnHead).css({
            'width': '60px'
        });
        $(actionTimeColumnHead).css({
            'width': '120px'
        });
        $(typeColumnHead).css({
            'width': '30px'
        });


    }



    function initTime() {
        var updateCurrentDateTime = function () {
            //从后台接受时间数

            var time = g_Var['currentTime'].toFullTimeFormat();
            $('#lblTime').html(time);
        }

        EzAccessor.getBasicInfo();

        var refreshCurrentTime = function () {
            // 时间加1
            g_Var['currentTime'] = new Date(
				g_Var['currentTime'].getFullYear(),
				g_Var['currentTime'].getMonth(),
				g_Var['currentTime'].getDate(),
				g_Var['currentTime'].getHours(),
				g_Var['currentTime'].getMinutes(),
				g_Var['currentTime'].getSeconds() + 1
				);

            updateCurrentDateTime();
        }

        refreshCurrentTime();
        setInterval(refreshCurrentTime, 1000);
    }

    function initiExplainText() {
        $('#explainText').defaultText('在这里说明特殊情况原因，正常情况考勤置空。');
    }

    function bindAttendanceConfig(attendanceConfig) {
       // 附上模板
        $("#tblAttendanceConfig").setTemplateElement("template");
        // 给模板加载数据
        $("#tblAttendanceConfig").processTemplate(attendanceConfig);
    }


    function initPage() {
        initTime();
        //初始化
        initiExplainText();

        EzAccessor.getBasicInfo();

        var dayInfo = EzAccessor.getDayInfo();
        $.tipDayInfo(dayInfo);
        var attendanceConfig = EzAccessor.getAttendanceConfig();
        bindAttendanceConfig(attendanceConfig);
       // 隐藏 非正常考勤提示标签

        EzTipsManager.addTipBox('#tip_Remind', 'tipRemind');
        EzTipsManager.addTipBox('#tip_Abnormal', 'tipAbnormal');
        EzTipsManager.addTipBox('#tip_Duplicated', 'tipDuplicated');

        EzTipsManager.showTipBox('tipRemind');
        $('#lblAbnormal').hide();

        $('#attendanceChange').freeContent({
            content: '#menu_changeAttendanceType',
            showArrow: true
        });

        updateCurrentStatus();
        updateAttendanceList();
    }



    function initPageEvent() {
        $('#btnCheck').click(function () {
            //提示内容
            $('#txtTimeNow').html(g_Var.currentTime.toFullDate() + " " + g_Var.currentTime.toFullTime());
            $('#txtAttendanceType').html(StaticResource.AttdendacneTypeResource[g_Var.attendanceType]);
            //对话框
            $('#dialog_confirmCheckAttendance').dialog({
                modal: true,
                resizable: false,
                height: 220,
                width: 300,
                buttons: {
                    '确定考勤': function () {
                        EzAccessor.doCheckAttendance();
                        $(this).dialog("close");
                    },
                    '取消': function () {
                        $(this).dialog("close");
                    }
                }
            });
        });

        $('#btnOnDuty').click(function () {
            changeAttendanceTypeCallback('onDuty');
        });
        $('#btnOffDuty').click(function () {
            changeAttendanceTypeCallback('offDuty');
        });
    }

    $(function () {
        initPage();
        initPageEvent();
    });
    </script>
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="PageHead" runat="server">
    <%
        Html.RenderPartial("_sayHello"); %>
    <div id="status-bar"><% Html.RenderPartial("_navigateTo"); %></div>
</asp:Content>
<asp:Content ID="Content5" ContentPlaceHolderID="PageContent" runat="server">
    <!-- 模板内容 -->
    <textarea id="template" style="display: none">
        <ul class="attendanceConfig">
            <li>上班时间： <span>{$T.ondutyTimeForward}</span> -- <span>{$T.ondutyTimeDelay}</span></li>
            <li>下班时间： <span>{$T.offdutyTimeForward}</span> -- <span></span>{$T.offdutyTimeDelay}</li>
        </ul>
    </textarea>
    <div id="page-head">
        <img src="../../Content/icons/candy_clock.png" style="width: 48x; height: 48px;"
            alt="time" />
        <span>现在时间：</span> <span id="timeDisplay">
            <span style="font-weight: bold; display: inline;" id="lblTime">
            </span>
        </span>
    </div>
    <div id="page-body">
        <ul id="attendanceInfo" class="fieldslist">
            <li>
                <div class="l">
                    考勤类型：
                </div>
                <div class="r" style="position: relative;">
                    <div id="attendanceChange">
                    </div>
                </div>
            </li>
            <li id="listRemark">
                <div class="l">
                    备注信息：</div>
                <div class="r">
                    <textarea id="explainText" class="f-input" cols="40" rows="2"></textarea>
                </div>
            </li>
            <li>
                <div class="c">
                    <input id="btnCheck" type="button" value="现在考勤！" />
                </div>
            </li>
        </ul>
        <hr />
        <div class="tableContainer" id="divAttendanceList">
        </div>
    </div>
    <div class="page-submit" style="display: none;">
        <input type="submit" value="提交" />&nbsp;或者&nbsp;<a>取消</a>
    </div>
</asp:Content>
<asp:Content ID="Content6" ContentPlaceHolderID="PageShortcut" runat="server">
</asp:Content>
<asp:Content ID="Content7" ContentPlaceHolderID="PageFoot" runat="server">
    <div id="menu_changeAttendanceType">
        <ul style="line-height: 30px; text-align: center;">
            <li><a id="btnOnDuty" href="#">上班</a></li>
            <li><a id="btnOffDuty" href="#">下班</a></li>
        </ul>
    </div>
    <div id="dialog_confirmCheckAttendance" title="EzDesk - 考勤" style="display: none;">
        <p class="p_title">
            <span class="ui-icon ui-icon-circle-check" style="float: left; margin: 0 7px 50px 0;">
            </span>确定考勤？
            <p class="p_body">
                现在时间是&nbsp;<span id="txtTimeNow" style="font-weight: bold;"></span></p>
            <p class="p_body">
                您将要进行&nbsp;<span id="txtAttendanceType" style="font-weight: bold; color: #090;"></span>&nbsp;考勤
            </p>
        </p>
    </div>
    <div id="tip_Remind" style="display: none;">
        <h1>
            考勤小贴士</h1>
        <div id="tblAttendanceConfig" class="jTemplatesTest">
        </div>
    </div>
    <div id="tip_Abnormal" style="display: none;" class="tip-warning">
        <h1>
            确定要进行考勤？</h1>
        <p class="indent">
            看起来现在并不是正常考勤时间，确定要考勤，请认真填写考勤备注！
        </p>
    </div>
    <div id="tip_Duplicated" style="display: none;" class="tip-info">
        <h1>
            已完成考勤</h1>
    </div>
</asp:Content>
